<script setup>
import { ref , onMounted, watch } from 'vue'
import { getAllClazz,addClazzApi ,getClazzByIdApi,getAllEmpApi,updateClazzApi,deleteClazzApi}from '@/api/clazz.js'
import { ElMessage,ElMessageBox } from 'element-plus';

/* 搜索表单 */
 const searchClazz=ref({
  name:'',
  begin:'',
  end:'',
  clazzDate:[]
 })
 const clazz=ref({
  name:'',
  room:'',
  beginDate:'',
  endDate:'',
  masterId:'',
  subject:''
 })
const page=ref(1)
const pageSize=ref(5)
const clazzTotal=ref(0)
/* 班级列表 */
const clazzList=ref([])
//表单可视化
const dialogFormVisible=ref(false)
//表单标题
const formTitle=ref('')

/* 员工列表 */
const empolyee=ref([])
/* 班主任列表 */
const masterList=ref([])
/* 表单实例 */
const clazzFormRef=ref()
const subjectList=ref([{name:'java',value:1},
                      {name:'前端',value:2},
                      {name:'大数据',value:3},
                      {name:'Python',value:4},
                      {name:'Go',value:5},
                      {name:'嵌入式',value:6}
                    ])

/* 查询员工 */
const getEmps=async()=>{
  const result=await getAllEmpApi()
  if(result.code){
    empolyee.value=result.data
    if(empolyee.value&&empolyee.value.length>0){
      console.log(empolyee)
      empolyee.value.forEach(emp=>{
          masterList.value.push({key:emp.name,value:emp.id})
      })
    }
  }
}
/* 查询班级 */
const search=async()=>{
const result=await getAllClazz(
  searchClazz.value.name,
  searchClazz.value.begin,
  searchClazz.value.end,
  page.value,
  pageSize.value
)
if(result.data){
  clazzTotal.value=result.data.total
  if(result.data.rows && result.data.rows.length > 0){
    clazzList.value=result.data.rows
  }
}
}
/* 钩子函数 */
onMounted(()=>{
  search()
  getEmps()
})
/* 给clazzDate绑定侦听 */
watch(()=>searchClazz.value.clazzDate,(data,preData)=>{
  if(searchClazz.value.clazzDate && searchClazz.value.clazzDate.length > 0){
    searchClazz.value.begin=searchClazz.value.clazzDate[0]
    searchClazz.value.end=searchClazz.value.clazzDate[1]
  }
})
/* 清空按钮 */
const clear=()=>{
searchClazz.value={
  name:'',
  begin:'',
  end:'',
  clazzDate:[]
}
search()
}
/* 页面展示条数变化时触发 */
const handleSizeChange=()=>{
search()
}
/* 页码发生变化时触发 */
const handleCurrentChange=()=>{
search()
}
/* 新增班级 */
const addClazz=()=>{
dialogFormVisible.value=true
clazz.value={
  name:'',
  room:'',
  beginDate:'',
  endDate:'',
  masterId:'',
  subject:''
}
formTitle.value='新增班级'
clazzFormRef.value.resetFields()
}
/* 数据校验规则 */
const rules = ref({
  name: [
    { required: true, message: '班级名称不能为空', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称长度为4-30位', trigger: 'blur' },
  ],
  room: [{ min: 1, max: 20, message: '班级教室长度为1-20位', trigger: 'blur' }],
  beginDate: [{ required: true, message: '开课时间不能为空', trigger: 'blur' }],
  endDate: [{ required: true, message: '结课时间不能为空', trigger: 'blur' }],
  subject: [{ required: true, message: '请选择学科', trigger: 'blur' }]
 })
 const saveClazz=async()=>{
  if (!clazzFormRef.value) return
     await clazzFormRef.value.validate(async (valid, fields) => {
        if (valid) {
          /* 校验成功 */
          let result;
          if(clazz.value.id){
             result=await updateClazzApi(clazz.value)
          }else{
            result=await addClazzApi(clazz.value)
          }
           if(result.code){
            ElMessage.success('添加成功')
            search()
            dialogFormVisible.value=false
           }else{
            ElMessage.error(result.msg)
           }
           
        } else {
          /* 校验失败 */
          ElMessage.error('校验失败,请重新输入')
          clazzFormRef.value.resetFields()
      }    
   }) 
 }
 const editClazz=async(id)=>{
  const result=await getClazzByIdApi(id)
  if(result.code){
    dialogFormVisible.value=true
    formTitle.value='修改班级'
    if(result.data){
      clazz.value=result.data
    }
  }
 }
 /* 删除班级 */
 const deleteClazz=(id)=>{
  ElMessageBox.confirm(
    '确定要删除改班级吗','提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const result=await deleteClazzApi(id)
      if(result.code){
        ElMessage.success('删除成功')
        search()
      }else{
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作已取消',
      })
    })
 }
</script>

<template>
  <h1>班级管理</h1>
  <div class="title">
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
    <el-form-item label="班级名称">
      <el-input v-model="searchClazz.name" placeholder="请输入班级名称" clearable />
    </el-form-item>
    <el-form-item label="结课时间" >
      <el-date-picker
        v-model="searchClazz.clazzDate"
        value-format="YYYY-MM-DD"
        type="daterange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>
  <el-button  type="primary" @click="addClazz">+ 新增班级</el-button>
  <div class="clazzTable">
   <el-table :data="clazzList" border style="width: 100%" >
     <el-table-column type="index" label="序号" width="80" align="center" />
     <el-table-column prop="name" label="班级名称" width="100" align="center"/>
     <el-table-column prop="room" label="班级教室" width="100" align="center"/>
     <el-table-column prop="masterName" label="班主任" width="100" align="center"/>
     <el-table-column prop="beginDate" label="开课时间" width="150" align="center"/>
     <el-table-column prop="endDate" label="结课时间" width="150" align="center"/>
     <el-table-column prop="status" label="状态"width="100" align="center"/>
     <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center"/>
     <el-table-column label="操作" align="center">
       <template #default="scope">
         <el-button size="small" type="primary" @click="editClazz(scope.row.id)">编辑</el-button>
         <el-button size="small" type="danger" @click="deleteClazz(scope.row.id)">删除 </el-button>
       </template>
     </el-table-column>
   </el-table>
  </div>
  <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5,10, 20, 30, 40,50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="clazzTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
  <!-- 新增/编辑表单 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500" align-center="true">
    <el-form ref="clazzFormRef" :model="clazz" :rules="rules" >
      <el-row >
          <el-col :span="24">
            <el-form-item label="班级名称" prop="name" ><!-- label-width="" -->
              <el-input v-model="clazz.name" placeholder="请输入班级名称,如:西安黑马javaEE就业100期"/>
            </el-form-item>
          </el-col>
      </el-row>
      
      <el-row >
          <el-col :span="24">
            <el-form-item label="班级教室" prop="room" ><!-- label-width="" -->
              <el-input v-model="clazz.room" placeholder="请填写班级教室"/>
            </el-form-item>
          </el-col>
      </el-row>
      <el-row >
          <el-col :span="24">
            <el-form-item label="开课时间"  prop="beginDate">
              <el-date-picker
                v-model="clazz.beginDate"
                type="date"
                placeholder="请选择开课时间"
                style="width: 100%;"
                value-format="YYYY-MM-DD"
               />
            </el-form-item>
          </el-col>
      </el-row>

      <el-row >
          <el-col :span="24">
            <el-form-item label="结课时间" prop="endDate">
              <el-date-picker
              v-model="clazz.endDate"
              type="date"
              placeholder="请选择结课时间时间"
              style="width: 100%;"
              value-format="YYYY-MM-DD"
             />
            </el-form-item>
          </el-col>
      </el-row>

      <el-row >
          <el-col :span="24">
            <el-form-item label="班主任" ><!-- label-width="" -->
              <el-select v-model="clazz.masterId" placeholder="请选择" style="width: 100%;" label-position="right" >
                <el-option v-for="(master, index) in masterList" :label="master.key" :value="master.value" />
              </el-select>
           </el-form-item>
          </el-col>
      </el-row>

      <el-row >
          <el-col :span="24">
            <el-form-item label="学科" label-position="right" prop="subject" >
              <el-select v-model="clazz.subject" placeholder="请选择" style="width: 100%;" label-position="right" >
                <el-option v-for="(subject, index) in subjectList"  :label="subject.name" :value="subject.value" />
             </el-select>
           </el-form-item>
          </el-col>
      </el-row>  
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveClazz">保存 </el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
     
</template>

<style scoped>
.title{
  margin: 20px 0;
}
.clazzTable{
  margin: 20px 0;
}
</style>